package com.liuyun.unixsocket;

import jnr.unixsocket.UnixSocketAddress;
import jnr.unixsocket.UnixSocketChannel;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * @author liuyun
 */
public class ClientActor implements Actor {
    private static final Logger LOGGER = Logger.getLogger(ClientActor.class.getName());
    private final UnixSocketChannel channel;

    public ClientActor(UnixSocketChannel channel) {
        this.channel = channel;
    }

    @Override
    public final boolean hasReady() {
        try {
            ByteBuffer buf = ByteBuffer.allocate(1024);
            int n;

            while ((n = channel.read(buf)) > 0) {
                UnixSocketAddress remote = channel.getRemoteSocketAddress();
                LOGGER.log(Level.INFO, "Read in {0} bytes from {1}", new Object[]{n, remote});

                if (n > 0) {
                    buf.flip();
                    channel.write(buf);
                    buf.clear();
                } else if (n < 0) {
                    return false;
                }
            }
        } catch (IOException ex) {
            ex.printStackTrace();
            return false;
        }
        return true;
    }
}
